<?php

class ManyToMany extends Join
{
	public $otherSideField;
	public $side;
	
	const LEFT = true;
	const RIGHT = false;
	
	public function __construct($field,$class,$otherSideField,$side)
	{
		parent::__construct($field,$class);
		$this->side = $side;
		$this->otherSideField  = $otherSideField;
	}
	
	public function generateJoinTableName()
	{
		$side1 = $this->entity.'_'.$this->field;
		$side2 = $this->class.'_'.$this->otherSideField;
		
		if($this->side == ManyToMany::LEFT)
			return $side1.'_'.$side2;
		else
			return $side2.'_'.$side1;
	}	

	public function useFieldForStatement($statement)
	{
		return false;
	}	
	
	public function load(Entity $entity)
	{
		if($this->class instanceof Entity)
		{
			$sql = new Select($this->class);
		} else {
			$sql = new Select(new $this->class());
		}
			
		$joinTableName = $this->generateJoinTableName();	
		
		$alias = $c->getMetaAlias();
		
		$sql->addJoin(new SQL_Join(SQL::JOIN_INNER,$joinTableName,$joinTableName,$this->field."Id",$this->class,"Id",$this->otherSideField."Id = ?"));
		$sql->addJoin(new SQL_Join(SQL::JOIN_INNER,$this->entity,$this->entity,"Id",$joinTableName,$this->otherSideField."Id"));
		$sql->addParam($entity->getId());
		
		$dao = new GenericDAO($this->class);
		return $dao->executeStatement($sql);		
	}

	public function postInit()
	{
		if($this->side == ManyToMany::RIGHT)
			return;

		$i = new TInt('id',4,null);
		$i->isPrimary = true;
		$i->isAutoIncrement = true;
		Map::setField($this->generateJoinTableName(),$i);	
		Map::setField($this->generateJoinTableName(),new TInt('active',1,1));
		Map::setField($this->generateJoinTableName(),new TDate('created',true));
		Map::setField($this->generateJoinTableName(),new TInt($this->field.'Id'));
		Map::setField($this->generateJoinTableName(),new TInt($this->otherSideField.'Id'));
		
		Map::setKeys($this->generateJoinTableName(),array($this->field=>array($this->field.'Id'),$this->otherSideField=>array($this->otherSideField.'Id')));
	}
	
	public function __toString()
	{
		return "";
	}		
}

?>